package org.mango;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.mango.handler.DiscardServerHandler;

/**
 * Created by meigang on 2019/8/7.
 */
public class DiscardServer {
    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1) 创建线程组，包括主线程组和工作线程组，主线程组用来accept连接，工作线程组用来handle连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2) 创建服务启动工具对象
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class) // (3) 设置boss隧道使用nio模型
                    .childHandler(new ChannelInitializer<SocketChannel>() { // (4) 设置work隧道要处理的handler顺序
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DiscardServerHandler());
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128) // (5) 设置boss隧道选项
                    .childOption(ChannelOption.SO_KEEPALIVE, true); // (6) 设置work隧道选项,例如长链接，使用keepalive


            ChannelFuture f = b.bind(port).sync(); // (7) 绑定端口并启动
            System.out.println("discard server is running on "+port+"...");
            //直到服务socket关闭
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }

        new DiscardServer(port).run();
    }
}
